package com.jaya.budan.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.jaya.budan.R;
import com.jaya.budan.base.BaseActivity;
import com.jaya.budan.connect.RequestConnect;
import com.jaya.budan.thirdpush.GenerateTestUserSig;
import com.jaya.budan.utils.ToolUtils;
import com.jaya.budan.utils.Utils;
import com.jaya.budan.utils.VolleyUtil;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMOfflinePushSettings;
import com.tencent.qcloud.tim.uikit.TUIKit;
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

public class Loading_Activity extends BaseActivity implements View.OnClickListener {

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0) {
                Intent intent = new Intent(Loading_Activity.this, LoginActivity.class);
                startActivity(intent);
                finish();
            }
        }
    };
    private String username, password, access_token;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading);
        SharedPreferences preferences = getSharedPreferences("user_limit", Context.MODE_PRIVATE);
        username = preferences.getString("username", "");
        password = preferences.getString("password", "");
        if (!ToolUtils.isEmpty(username) &&  !ToolUtils.isEmpty(password)){
            JSONObject object = new JSONObject();
            try {
                object.put("username", username);
                object.put("password", password);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            postData(object);
        } else {
            handler.sendEmptyMessageDelayed(0, 3000);
        }
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back:
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 网络请求
     * @param object
     */
    private void postData(JSONObject object) {
        Log.d("login", object.toString());
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, RequestConnect.login_Url, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("login", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONObject info = jsonObject.getJSONObject("info");
                        access_token = info.getString("access_token");
                        int id = info.getInt("id");
                        boolean is_over = info.getBoolean("is_over");
                        if (is_over){
                            Intent intent = new Intent(Loading_Activity.this, MainActivity.class);//资料完整,跳转首页
                            intent.putExtra("access_token", access_token);
                            startActivity(intent);
                            finish();
                        } else {
                            Intent intent = new Intent(Loading_Activity.this, Fill_Information_Activity.class);//资料不完整，自动跳转至资料填写页面
                            intent.putExtra("access_token", access_token);
                            startActivity(intent);
                        }
                        JSONObject object = new JSONObject();
                        try {
                            object.put("reg_id", JPushInterface.getRegistrationID(Loading_Activity.this));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        postUploadJpushData(object, id + "");
                        // 获取userSig函数
                        String userSig = GenerateTestUserSig.genTestUserSig(id + "");
                        TIMManager.getInstance().login(id + "", userSig, new TIMCallBack() {
                            @Override
                            public void onError(int code, String desc) {
                                ToolUtils.showToast(Loading_Activity.this, "登录失败, errCode = " + code + ", errInfo = " + desc);
                                if (code == 6208){
                                    Log.d("login", "被其他人踢开");
                                }
                            }

                            @Override
                            public void onSuccess() {
//                                ToolUtils.showToast(LoginActivity.this, "登录成功");
                            }
                        });
                        SharedPreferences preferences = getSharedPreferences("user_limit", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putString("username", username);
                        editor.putString("password", password);
                        editor.putString("access_token", access_token);
                        editor.apply();
                        TUIKit.login(id + "", userSig, new IUIKitCallBack() {
                            @Override
                            public void onError(String module, final int code, final String desc) {
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        ToolUtils.showToast(Loading_Activity.this, "登录失败, errCode = " + code + ", errInfo = " + desc);
                                    }
                                });
                                ToolUtils.showToast(Loading_Activity.this, "登录失败, errCode = " + code + ", errInfo = " + desc);
                            }
                            @Override
                            public void onSuccess(Object data) {
                                ToolUtils.showToast(Loading_Activity.this, "登录成功");
                                TIMOfflinePushSettings settings = new TIMOfflinePushSettings();
                                //开启离线推送
                                settings.setEnabled(true);
                                //设置收到 C2C 离线消息时的提示声音，以把声音文件放在 res/raw 文件夹下为例
                                settings.setC2cMsgRemindSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.drawable.ic_launcher_background));
                                //设置收到群离线消息时的提示声音，以把声音文件放在 res/raw 文件夹下为例
//                                settings.setGroupMsgRemindSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.drawable.ic_launcher_background));
                                TIMManager.getInstance().setOfflinePushSettings(settings);
                                TIMManager.getInstance().getConversation(
                                        TIMConversationType.C2C,    //会话类型：单聊
                                        id+"");
                            }
                        });
                    } else if (code == 400){ //账号未注册
                        ToolUtils.showToast(Loading_Activity.this, message);
                        Intent intent = new Intent(Loading_Activity.this, LoginActivity.class);
                        startActivity(intent);
                        finish();
                    } else if (code == 500){ //账号已被删除
                        ToolUtils.showToast(Loading_Activity.this, message);
                        Intent intent = new Intent(Loading_Activity.this, LoginActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        ToolUtils.showToast(Loading_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(Loading_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    /**
     * 网络请求
     */
    private void postUploadJpushData(JSONObject object, String uid) {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, RequestConnect.upload_Jpush_Url + access_token, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("login", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JPushInterface.setAlias(getApplicationContext(), uid, new TagAliasCallback() {
                            @Override
                            public void gotResult(int arg0, String arg1, Set<String> arg2) {
                            }
                        });
                    } else {
                        ToolUtils.showToast(Loading_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(Loading_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }
}
